package com.itxx.thread4;
    //lock  锁解决安全问题

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketDemo2 implements Runnable {
    private static int sticket = 100;
    private static Object obj = new Object();
    private static Lock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (sticket == 0) {
                    System.out.println(Thread.currentThread().getName() + ":票卖完了");
                    break;
                } else if (sticket > 0) {
                    try {
                        Thread.sleep(10);
                        System.out.println(Thread.currentThread().getName() + "正在卖" + sticket + "张票");
                        sticket--;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } finally {
                lock.unlock();
            }

        }
    }
}

class Demo1 {
    public static void main(String[] args) {
        TicketDemo tt = new TicketDemo();
        Thread t1 = new Thread(tt, "窗口1");
        Thread t2 = new Thread(tt, "窗口2");
        Thread t3 = new Thread(tt, "窗口3");
        t1.start();
        t2.start();
        t3.start();
    }
}

